/**
 * 中国象棋AI算法实现
 * 使用改进的Minimax算法 + Alpha-Beta剪枝 + 高级评估系统
 * 包含开局库、残局库、战术识别等高级功能
 */

import { COLORS, PIECE_TYPES } from '../constants/pieces.js';
import { getAllValidMoves, makeMove } from '../rules/gameRules.js';
import { cloneBoard } from '../engine/BoardUtils.js';
import { AI_DIFFICULTY } from '../constants/gameConfig.js';

export class ChessAI {
  constructor(difficulty = AI_DIFFICULTY.MEDIUM) {
    this.difficulty = difficulty;
    this.maxDepth = Math.min(difficulty.depth, 6); // 允许更深的搜索以提升AI实力
    this.transpositionTable = new Map();
    this.killerMoves = [];
    this.historyTable = {};
    this.pvTable = {};
    this.moveCount = 0;
    this.nodeCount = 0;
    this.maxNodes = this.calculateMaxNodes(difficulty); // 根据难度动态调整节点限制
    
    // 初始化杀手移动表
    for (let depth = 0; depth < this.maxDepth + 2; depth++) {
      this.killerMoves[depth] = [];
    }
    
    // 初始化开局库
    this.initializeOpeningBook();
    
    // 初始化位置价值表
    this.initializePositionTables();
  }

  /**
   * 根据难度计算最大节点数
   */
  calculateMaxNodes(difficulty) {
    const nodeMap = {
      1: 10000,   // BEGINNER
      2: 20000,   // EASY
      3: 50000,   // MEDIUM
      4: 100000,  // HARD
      5: 200000,  // EXPERT
      6: 300000,  // MASTER
      7: 500000   // GRANDMASTER
    };
    return nodeMap[difficulty.level] || 50000;
  }

  /**
   * 获取最佳移动 (性能优化版)
   */
  getBestMove(board, color, moveHistory = [], timeLimit = 2000) { // 添加移动历史参数
    this.moveCount++;
    this.nodeCount = 0;
    this.moveHistory = moveHistory; // 保存移动历史
    const startTime = Date.now();
    
    // 🔍 威胁感知：扫描所有对手威胁
    const threats = this.findOpponentThreats(board, color);
    if (threats.length > 0) {
      console.log(`\n🎯 发现 ${threats.length} 个威胁:`);
      threats.slice(0, 3).forEach((threat, idx) => {
        console.log(`   ${idx + 1}. ${threat.piece.name}(${threat.position.row},${threat.position.col}) - ${threat.description} [威胁${Math.round(threat.threatLevel)}分]`);
      });
    }
    
    // 快速情况处理
    
    // 1. 开局库 (前8步)
    if (this.moveCount <= 8) {
      const openingMove = this.getOpeningMove(board, color);
      if (openingMove) {
        console.log(`📚 开局库移动 (${Date.now() - startTime}ms)`);
        return openingMove;
      }
    }
    
    // 2. 获取所有合法移动
    const allMoves = getAllValidMoves(board, color);
    
    if (allMoves.length === 0) {
      return null; // 无移动
    }
    
    if (allMoves.length === 1) {
      console.log(`🎯 唯一移动 (${Date.now() - startTime}ms)`);
      return allMoves[0];
    }
    
    // 3. 紧急移动检查 (被将军、立即获胜、免费吃子)
    const urgentMove = this.findUrgentMoveFast(board, color);
    if (urgentMove) {
      console.log(`⚡ 紧急移动 (${Date.now() - startTime}ms)`);
      return urgentMove;
    }
    
    // 4. 快速搜索 - 限制候选移动数量
    const orderedMoves = this.getOrderedMoves(board, color, 0);
    const candidateMoves = orderedMoves.slice(0, Math.min(15, orderedMoves.length)); // 只考虑前15个最佳移动
    
    let bestMove = candidateMoves[0];
    let bestValue = -Infinity;
    
    // 5. 迭代深化搜索 (优化版)
    for (let depth = 1; depth <= this.maxDepth; depth++) {
      const depthStartTime = Date.now();
      let depthBestMove = null;
      let depthBestValue = -Infinity;
      
      // 检查时间和节点限制
      if (Date.now() - startTime > timeLimit * 0.7 || this.nodeCount > this.maxNodes) {
        break;
      }
      
      for (let i = 0; i < candidateMoves.length; i++) {
        const move = candidateMoves[i];
        
        // 时间检查
        if (Date.now() - startTime > timeLimit * 0.8) break;
        
        const newBoard = cloneBoard(board);
        const moveResult = makeMove(newBoard, move.from, move.to);
        
        if (moveResult.success) {
          const value = -this.searchMoveFast(newBoard, depth - 1, -Infinity, Infinity, 
                                            color === COLORS.RED ? COLORS.BLACK : COLORS.RED, 
                                            startTime, timeLimit);
          
          if (value > depthBestValue) {
            depthBestValue = value;
            depthBestMove = move;
          }
        }
        
        // 如果明显有最佳移动，可以提前退出
        if (i >= 5 && depthBestValue > bestValue + 200) {
          break;
        }
      }
      
      if (depthBestMove) {
        bestMove = depthBestMove;
        bestValue = depthBestValue;
      }
      
      // 如果这一层搜索时间过长，停止加深
      if (Date.now() - depthStartTime > timeLimit / 3) {
        break;
      }
    }
    
    // 应用难度随机因子
    if (this.difficulty.randomFactor && this.difficulty.randomFactor > 0 && Math.random() < this.difficulty.randomFactor) {
      const topMoves = candidateMoves.slice(0, 3);
      bestMove = topMoves[Math.floor(Math.random() * topMoves.length)];
    }
    
    const elapsed = Date.now() - startTime;
    console.log(`🎯 AI选择: ${this.moveToString(bestMove)} (${elapsed}ms, ${this.nodeCount}节点)`);
    
    return bestMove;
  }

  /**
   * 快速搜索函数 (性能优化版)
   */
  searchMoveFast(board, depth, alpha, beta, color, startTime, timeLimit) {
    this.nodeCount++;
    
    // 严格的时间和节点限制
    if (Date.now() - startTime > timeLimit || this.nodeCount > this.maxNodes) {
      return this.evaluateBoardFast(board, color);
    }

    // 置换表查询 (简化版)
    const boardHash = this.getBoardHashFast(board);
    const ttEntry = this.transpositionTable.get(boardHash);
    if (ttEntry && ttEntry.depth >= depth) {
      return ttEntry.value;
    }

    // 叶子节点
    if (depth <= 0) {
      return this.quiescenceSearchFast(board, alpha, beta, color, 2); // 减少静止搜索深度
    }

    const moves = this.getOrderedMovesFast(board, color);
    
    if (moves.length === 0) {
      return this.isInCheck(board, color) ? -10000 : 0;
    }

    let bestValue = -Infinity;
    
    // 限制搜索的移动数量
    const searchMoves = moves.slice(0, Math.min(12, moves.length));

    for (let i = 0; i < searchMoves.length; i++) {
      const move = searchMoves[i];
      
      // 时间检查
      if (Date.now() - startTime > timeLimit * 0.9) break;
      
      const newBoard = cloneBoard(board);
      const moveResult = makeMove(newBoard, move.from, move.to);
      
      if (moveResult.success) {
        let value;
        
        // 简化的搜索
        if (i === 0) {
          value = -this.searchMoveFast(newBoard, depth - 1, -beta, -alpha, 
                                      color === COLORS.RED ? COLORS.BLACK : COLORS.RED,
                                      startTime, timeLimit);
        } else {
          // 零窗口搜索
          value = -this.searchMoveFast(newBoard, depth - 1, -alpha - 1, -alpha, 
                                      color === COLORS.RED ? COLORS.BLACK : COLORS.RED,
                                      startTime, timeLimit);
          if (value > alpha && value < beta) {
            value = -this.searchMoveFast(newBoard, depth - 1, -beta, -alpha, 
                                        color === COLORS.RED ? COLORS.BLACK : COLORS.RED,
                                        startTime, timeLimit);
          }
        }
        
        bestValue = Math.max(bestValue, value);
        alpha = Math.max(alpha, value);
        
        if (alpha >= beta) {
          break; // 剪枝
        }
      }
    }

    // 简化的置换表存储
    if (this.transpositionTable.size < 5000) { // 限制置换表大小
      this.transpositionTable.set(boardHash, {
        value: bestValue,
        depth: depth
      });
    }

    return bestValue;
  }

  /**
   * 主搜索函数 (原版本，保留备用)
   */
  searchMove(board, depth, alpha, beta, color, startTime, timeLimit, allowNull = true) {
    // 时间检查
    if (Date.now() - startTime > timeLimit) {
      return this.evaluateBoard(board, color);
    }

    // 置换表查询
    const boardHash = this.getBoardHash(board);
    const ttEntry = this.transpositionTable.get(boardHash);
    if (ttEntry && ttEntry.depth >= depth) {
      if (ttEntry.flag === 'EXACT') return ttEntry.value;
      if (ttEntry.flag === 'LOWERBOUND' && ttEntry.value >= beta) return ttEntry.value;
      if (ttEntry.flag === 'UPPERBOUND' && ttEntry.value <= alpha) return ttEntry.value;
    }

    // 叶子节点评估
    if (depth <= 0) {
      return this.quiescenceSearch(board, alpha, beta, color, 4);
    }

    const moves = this.getOrderedMoves(board, color, depth);
    
    if (moves.length === 0) {
      // 检查是否被将军
      if (this.isInCheck(board, color)) {
        return -10000 + (this.maxDepth - depth); // 被将死，距离越远惩罚越小
      }
      return 0; // 和棋
    }

    let bestValue = -Infinity;
    let bestMove = null;
    let flag = 'UPPERBOUND';

    // Null Move Pruning (空移剪枝)
    if (allowNull && depth >= 3 && !this.isInCheck(board, color)) {
      const nullValue = -this.searchMove(board, depth - 3, -beta, -beta + 1, 
                                        color === COLORS.RED ? COLORS.BLACK : COLORS.RED, 
                                        startTime, timeLimit, false);
      if (nullValue >= beta) {
        return beta;
      }
    }

    for (let i = 0; i < moves.length; i++) {
      const move = moves[i];
      const newBoard = cloneBoard(board);
      const moveResult = makeMove(newBoard, move.from, move.to);
      
      if (moveResult.success) {
        let value;
        
        // PVS (Principal Variation Search)
        if (i === 0) {
          value = -this.searchMove(newBoard, depth - 1, -beta, -alpha, 
                                  color === COLORS.RED ? COLORS.BLACK : COLORS.RED,
                                  startTime, timeLimit);
        } else {
          // 零窗口搜索
          value = -this.searchMove(newBoard, depth - 1, -alpha - 1, -alpha, 
                                  color === COLORS.RED ? COLORS.BLACK : COLORS.RED,
                                  startTime, timeLimit);
          
          // 如果零窗口搜索失败，则重新搜索
          if (value > alpha && value < beta) {
            value = -this.searchMove(newBoard, depth - 1, -beta, -alpha, 
                                    color === COLORS.RED ? COLORS.BLACK : COLORS.RED,
                                    startTime, timeLimit);
          }
        }
        
        if (value > bestValue) {
          bestValue = value;
          bestMove = move;
        }
        
        alpha = Math.max(alpha, value);
        
        if (alpha >= beta) {
          // 更新杀手移动
          this.updateKillerMove(move, depth);
          // 更新历史启发
          this.updateHistory(move, depth);
          flag = 'LOWERBOUND';
          break;
        }
        
        if (alpha > -Infinity) {
          flag = 'EXACT';
        }
      }
    }

    // 存入置换表
    this.transpositionTable.set(boardHash, {
      value: bestValue,
      depth: depth,
      flag: flag,
      bestMove: bestMove
    });

    return bestValue;
  }

  /**
   * 静止搜索 (处理战术组合)
   */
  quiescenceSearch(board, alpha, beta, color, depth) {
    const standPat = this.evaluateBoard(board, color);
    
    if (depth <= 0 || standPat >= beta) {
      return standPat;
    }
    
    alpha = Math.max(alpha, standPat);
    
    // 只考虑吃子移动
    const captures = this.getCaptureMoves(board, color);
    
    for (const move of captures) {
      const newBoard = cloneBoard(board);
      const moveResult = makeMove(newBoard, move.from, move.to);
      
      if (moveResult.success) {
        const value = -this.quiescenceSearch(newBoard, -beta, -alpha, 
                                           color === COLORS.RED ? COLORS.BLACK : COLORS.RED, 
                                           depth - 1);
        
        if (value >= beta) {
          return beta;
        }
        
        alpha = Math.max(alpha, value);
      }
    }
    
    return alpha;
  }

  /**
   * 获取有序移动（高级移动排序）
   */
  getOrderedMoves(board, color, depth = 0) {
    const moves = getAllValidMoves(board, color);
    
    // 为每个移动评分并排序
    const scoredMoves = moves.map(move => ({
      move,
      score: this.scoreMoveForOrdering(board, move, color, depth)
    }));
    
    // 按评分降序排序
    scoredMoves.sort((a, b) => b.score - a.score);
    
    return scoredMoves.map(sm => sm.move);
  }

  /**
   * 为移动排序打分 - 智能战术版
   */
  scoreMoveForOrdering(board, move, color, depth) {
    let score = 0;
    
    const piece = board[move.from.row][move.from.col];
    const target = board[move.to.row][move.to.col];
    const opponentColor = color === COLORS.RED ? COLORS.BLACK : COLORS.RED;
    
    // ==================== 战术优先级（高到低） ====================
    
    // 【最高优先级】将军和将死
    const newBoard = cloneBoard(board);
    if (makeMove(newBoard, move.from, move.to).success) {
      if (this.isInCheck(newBoard, opponentColor)) {
        // 检查是否为将死
        const opponentMoves = getAllValidMoves(newBoard, opponentColor);
        if (opponentMoves.length === 0) {
          score += 1000000; // 将死！必胜！
          console.log('🎯 发现将死机会！');
        } else {
          score += 8000; // 将军，给对手施压
        }
      }
    }
    
    // 【次高优先级】吃子 - 但要考虑交换价值
    if (target) {
      const captureValue = this.getPieceValue(target);
      const attackerValue = this.getPieceValue(piece);
      
      // 基础吃子分数
      score += captureValue * 100;
      
      // 检查吃子后是否安全（会不会被吃回）
      if (this.isPieceSafeAfterMove(newBoard, move.to, color)) {
        score += captureValue * 50; // 安全吃子，额外奖励
      } else {
        // 不安全的吃子，评估交换
        const exchangeValue = captureValue - attackerValue;
        if (exchangeValue > 0) {
          score += exchangeValue * 30; // 有利交换
        } else if (exchangeValue < 0) {
          score += exchangeValue * 50; // 不利交换，严重惩罚
        }
      }
    }
    
    // 【超高优先级】驱逐/攻击威胁性的敌方棋子！
    if (target) {
      // 全面评估这个目标的威胁程度
      const invasionDepth = this.evaluateInvasionDepth(move.to, opponentColor);
      const controlled = this.getControlledPieces(board, move.to, color);
      const posDanger = this.evaluatePositionDanger(move.to, color);
      
      const captureValue = this.getPieceValue(target);
      let captureBonus = 0;
      
      // 入侵威胁
      if (invasionDepth > 0) {
        captureBonus += invasionDepth * captureValue * 100;
      }
      
      // 控制威胁
      if (controlled.count > 0) {
        captureBonus += controlled.totalValue * 80;
      }
      
      // 位置威胁
      if (posDanger > 0) {
        captureBonus += posDanger * captureValue * 50;
      }
      
      score += captureBonus;
      
      // 详细输出
      if (captureBonus > 0) {
        const reasons = [];
        if (invasionDepth > 0) reasons.push(`入侵${invasionDepth}级`);
        if (controlled.count > 0) reasons.push(`威胁${controlled.count}子`);
        if (posDanger > 0) reasons.push(`危险位置${posDanger}级`);
        console.log(`🚨 吃掉威胁棋子: ${target.name}(${move.to.row},${move.to.col}) - ${reasons.join(', ')}`);
      }
    }
    
    // 【高优先级】逃离威胁 - 拯救被威胁的高价值棋子
    if (this.isPieceUnderThreat(board, move.from, color)) {
      const pieceValue = this.getPieceValue(piece);
      score += pieceValue * 80; // 逃离威胁！非常重要！
      console.log(`💨 逃离威胁: ${piece.name} 从 (${move.from.row},${move.from.col})`);
      
      // 如果移动到安全位置，额外奖励
      if (this.isPieceSafeAfterMove(newBoard, move.to, color)) {
        score += pieceValue * 40; // 成功逃到安全地带
      }
    }
    
    // 【高优先级】反击 - 对手刚吃了我的子，反击他的攻击棋子
    if (this.moveHistory && this.moveHistory.length > 0) {
      const lastMove = this.moveHistory[this.moveHistory.length - 1];
      if (lastMove) {
        // 对手刚吃了我的子
        const opponentPiece = board[lastMove.to.row]?.[lastMove.to.col];
        if (opponentPiece && move.to.row === lastMove.to.row && move.to.col === lastMove.to.col) {
          score += 15000; // 立即反击！
          console.log(`⚔️ 反击对手的攻击棋子 (${lastMove.to.row},${lastMove.to.col})`);
        }
      }
    }
    
    // 【高优先级】驱赶/威胁深入己方的敌方棋子（即使不吃子）
    const opponentThreats = this.findOpponentThreats(board, color);
    for (const threat of opponentThreats) {
      // 检查这步棋能否威胁到这个危险棋子
      const myMovesAfter = getAllValidMoves(newBoard, color);
      const canThreaten = myMovesAfter.some(m => 
        m.to.row === threat.position.row && m.to.col === threat.position.col
      );
      
      if (canThreaten) {
        const threatScore = threat.threatLevel * 50; // 使用综合威胁等级
        score += threatScore; // 威胁/驱赶威胁棋子
        console.log(`⚔️ 驱赶威胁: ${threat.piece.name}(${threat.position.row},${threat.position.col}) - ${threat.description}`);
      }
    }
    
    // 【中优先级】威胁对手高价值棋子
    const threatenedPieces = this.getThreatenedPiecesAfterMove(newBoard, color);
    for (const threatenedPiece of threatenedPieces) {
      const threatValue = this.getPieceValue(threatenedPiece);
      if (threatValue >= 400) { // 威胁车/马/炮
        score += threatValue * 20;
      }
    }
    
    // 【中优先级】保护己方重要棋子
    const protectedPieces = this.getProtectedPiecesAfterMove(newBoard, move.to, color);
    for (const protectedPiece of protectedPieces) {
      if (this.isPieceUnderThreat(board, protectedPiece.position, color)) {
        score += this.getPieceValue(protectedPiece) * 15; // 保护被威胁的棋子
      }
    }
    
    // 【战术智慧】避免无意义的撤回移动
    if (this.moveHistory && this.moveHistory.length > 0) {
      const lastMove = this.moveHistory[this.moveHistory.length - 1];
      
      // 只有在没有战术意义时才惩罚撤回
      if (lastMove && 
          move.from.row === lastMove.to.row && 
          move.from.col === lastMove.to.col &&
          move.to.row === lastMove.from.row && 
          move.to.col === lastMove.from.col) {
        
        // 如果这个棋子正被威胁，允许撤回（逃跑）
        if (!this.isPieceUnderThreat(board, move.from, color)) {
          score -= 5000; // 无意义的撤回
        }
      }
    }
    
    // 【基础评估】位置价值改进
    const fromValue = this.getPositionValue(piece, move.from.row, move.from.col);
    const toValue = this.getPositionValue(piece, move.to.row, move.to.col);
    score += (toValue - fromValue) * 10;
    
    // 【基础评估】中心控制
    if (this.isCenterSquare(move.to.row, move.to.col)) {
      score += 50;
    }
    
    // 【开局策略】发展棋子
    if (this.moveCount < 15) {
      if (!this.isEdgeSquare(move.to.row, move.to.col)) {
        score += 20; // 鼓励向中心发展
      }
    }
    
    // 置换表和历史启发（辅助）
    const boardHash = this.getBoardHash(board);
    const ttEntry = this.transpositionTable.get(boardHash);
    if (ttEntry && ttEntry.bestMove && this.movesEqual(move, ttEntry.bestMove)) {
      score += 3000;
    }
    
    if (this.isKillerMove(move, depth)) {
      score += 2000;
    }
    
    const historyKey = this.getMoveKey(move);
    score += (this.historyTable[historyKey] || 0);
    
    return score;
  }
  
  /**
   * 检查棋子在移动后是否安全
   */
  isPieceSafeAfterMove(board, position, color) {
    const opponentColor = color === COLORS.RED ? COLORS.BLACK : COLORS.RED;
    const opponentMoves = getAllValidMoves(board, opponentColor);
    
    return !opponentMoves.some(move => 
      move.to.row === position.row && move.to.col === position.col
    );
  }
  
  /**
   * 检查棋子当前是否被威胁
   */
  isPieceUnderThreat(board, position, color) {
    const opponentColor = color === COLORS.RED ? COLORS.BLACK : COLORS.RED;
    const opponentMoves = getAllValidMoves(board, opponentColor);
    
    return opponentMoves.some(move => 
      move.to.row === position.row && move.to.col === position.col
    );
  }
  
  /**
   * 获取移动后威胁到的对手棋子
   */
  getThreatenedPiecesAfterMove(board, color) {
    const myMoves = getAllValidMoves(board, color);
    const threatenedPieces = [];
    
    for (const move of myMoves) {
      const target = board[move.to.row][move.to.col];
      if (target && target.color !== color) {
        threatenedPieces.push(target);
      }
    }
    
    return threatenedPieces;
  }
  
  /**
   * 获取移动后保护到的己方棋子
   */
  getProtectedPiecesAfterMove(board, position, color) {
    const myMoves = getAllValidMoves(board, color);
    const protectedPieces = [];
    
    // 简化实现：检查这个位置能攻击到哪些己方棋子位置
    // （在实际象棋中，保护的概念比较复杂，这里简化处理）
    
    return protectedPieces;
  }
  
  /**
   * 评估棋子的入侵深度（核心战术功能）
   * 返回：0-6的深度值，越大表示越深入对手阵地
   */
  evaluateInvasionDepth(position, pieceColor) {
    const { row } = position;
    
    if (pieceColor === COLORS.RED) {
      // 红方棋子，行数越小越深入黑方
      // 红方底线是9，黑方底线是0
      // 如果在0-2行，深度为 6-4
      // 如果在3-4行，深度为 3-2
      // 如果在5+行，深度为 1-0
      if (row <= 2) return 6 - row; // 深度6, 5, 4
      if (row <= 4) return 4 - row; // 深度1, 0
      return 0;
    } else {
      // 黑方棋子，行数越大越深入红方
      // 黑方底线是0，红方底线是9
      if (row >= 7) return row - 6; // 深度1, 2, 3
      if (row >= 5) return row - 4; // 深度1, 0
      return 0;
    }
  }
  
  /**
   * 全面评估对手棋子的威胁（不只是入侵深度）
   * 包括：位置威胁、控制力、对重要棋子的威胁等
   */
  findOpponentThreats(board, myColor) {
    const opponentColor = myColor === COLORS.RED ? COLORS.BLACK : COLORS.RED;
    const threats = [];
    
    for (let row = 0; row < 10; row++) {
      for (let col = 0; col < 9; col++) {
        const piece = board[row][col];
        if (piece && piece.color === opponentColor) {
          // 1. 入侵深度评估
          const invasionDepth = this.evaluateInvasionDepth({ row, col }, opponentColor);
          
          // 2. 控制力评估 - 这个棋子能威胁多少我方棋子
          const controlledMyPieces = this.getControlledPieces(board, { row, col }, myColor);
          
          // 3. 位置危险度 - 是否在关键位置（九宫格附近、中心等）
          const positionDanger = this.evaluatePositionDanger({ row, col }, myColor);
          
          // 4. 综合威胁等级
          const pieceValue = this.getPieceValue(piece);
          const threatLevel = 
            invasionDepth * pieceValue * 1.0 +           // 入侵威胁
            controlledMyPieces.totalValue * 0.8 +        // 控制威胁
            positionDanger * pieceValue * 0.5;           // 位置威胁
          
          // 只要有任何威胁因素，就加入列表
          if (invasionDepth > 0 || controlledMyPieces.count > 0 || positionDanger > 0) {
            threats.push({
              piece,
              position: { row, col },
              invasionDepth,
              controlledPieces: controlledMyPieces.count,
              controlledValue: controlledMyPieces.totalValue,
              positionDanger,
              threatLevel,
              description: this.describeThreat(piece, invasionDepth, controlledMyPieces, positionDanger)
            });
          }
        }
      }
    }
    
    // 按威胁等级排序
    threats.sort((a, b) => b.threatLevel - a.threatLevel);
    
    return threats;
  }
  
  /**
   * 评估棋子控制了多少对手的棋子
   */
  getControlledPieces(board, position, targetColor) {
    const piece = board[position.row][position.col];
    if (!piece) return { count: 0, totalValue: 0, pieces: [] };
    
    // 获取这个棋子的所有可能移动
    const moves = getAllValidMoves(board, piece.color);
    const controlledPieces = [];
    let totalValue = 0;
    
    for (const move of moves) {
      // 只考虑从这个位置出发的移动
      if (move.from.row === position.row && move.from.col === position.col) {
        const target = board[move.to.row][move.to.col];
        if (target && target.color === targetColor) {
          controlledPieces.push(target);
          totalValue += this.getPieceValue(target);
        }
      }
    }
    
    return {
      count: controlledPieces.length,
      totalValue,
      pieces: controlledPieces
    };
  }
  
  /**
   * 评估位置的危险度（对我方而言）
   */
  evaluatePositionDanger(position, myColor) {
    const { row, col } = position;
    let danger = 0;
    
    // 1. 九宫格附近危险度
    const palaceRows = myColor === COLORS.RED ? [7, 8, 9] : [0, 1, 2];
    const palaceCols = [3, 4, 5];
    
    if (palaceRows.includes(row) && palaceCols.includes(col)) {
      danger += 3; // 在九宫格内，极度危险！
    } else if (palaceRows.includes(row)) {
      danger += 2; // 在九宫格所在行
    }
    
    // 2. 中心控制危险度
    if (col >= 3 && col <= 5 && row >= 3 && row <= 6) {
      danger += 1; // 控制中心
    }
    
    // 3. 底线危险度
    const bottomRow = myColor === COLORS.RED ? 9 : 0;
    const distance = Math.abs(row - bottomRow);
    if (distance <= 2) {
      danger += (3 - distance); // 越靠近底线越危险
    }
    
    return danger;
  }
  
  /**
   * 描述威胁（用于调试）
   */
  describeThreat(piece, invasionDepth, controlledPieces, positionDanger) {
    const parts = [];
    
    if (invasionDepth > 0) {
      parts.push(`入侵深度${invasionDepth}`);
    }
    
    if (controlledPieces.count > 0) {
      parts.push(`威胁${controlledPieces.count}个棋子(${controlledPieces.totalValue}分)`);
    }
    
    if (positionDanger > 0) {
      parts.push(`危险位置(${positionDanger}级)`);
    }
    
    return parts.join(', ');
  }

  /**
   * 高级棋盘评估函数
   */
  evaluateBoard(board, color) {
    let material = 0;
    let position = 0;
    let mobility = 0;
    let safety = 0;
    let development = 0;
    let invasionPenalty = 0; // 新增：入侵惩罚
    
    const myColor = color;
    const opponentColor = color === COLORS.RED ? COLORS.BLACK : COLORS.RED;
    
    // 1. 子力价值评估 + 入侵威胁评估
    for (let row = 0; row < 10; row++) {
      for (let col = 0; col < 9; col++) {
        const piece = board[row][col];
        if (piece) {
          const pieceValue = this.getPieceValue(piece);
          const posValue = this.getAdvancedPositionValue(piece, row, col);
          
          if (piece.color === myColor) {
            material += pieceValue;
            position += posValue;
            
            // 奖励我方棋子深入对手阵地
            const myInvasion = this.evaluateInvasionDepth({ row, col }, myColor);
            if (myInvasion > 0) {
              position += myInvasion * pieceValue * 0.5; // 进攻奖励
            }
          } else {
            material -= pieceValue;
            position -= posValue;
            
            // 严厉惩罚对手棋子深入我方阵地！
            const opponentInvasion = this.evaluateInvasionDepth({ row, col }, opponentColor);
            if (opponentInvasion > 0) {
              invasionPenalty += opponentInvasion * pieceValue * 2; // 防守惩罚，系数更高！
            }
          }
        }
      }
    }
    
    // 2. 机动性评估
    const myMoves = getAllValidMoves(board, myColor).length;
    const oppMoves = getAllValidMoves(board, opponentColor).length;
    mobility = (myMoves - oppMoves) * 5;
    
    // 3. 王安全评估
    const myKingSafety = this.evaluateKingSafety(board, myColor);
    const oppKingSafety = this.evaluateKingSafety(board, opponentColor);
    safety = myKingSafety - oppKingSafety;
    
    // 4. 发展评估（开局阶段）
    if (this.moveCount < 20) {
      development = this.evaluateDevelopment(board, myColor) - 
                   this.evaluateDevelopment(board, opponentColor);
    }
    
    // 5. 特殊位置奖励
    const specialBonus = this.evaluateSpecialPositions(board, myColor) - 
                        this.evaluateSpecialPositions(board, opponentColor);
    
    // 6. 残局评估
    const endgameBonus = this.isEndgame(board) ? this.evaluateEndgame(board, myColor) : 0;
    
    const totalScore = material + position + mobility + safety + development + specialBonus + endgameBonus - invasionPenalty;
    
    // 添加小的随机因子避免重复
    const randomFactor = (Math.random() - 0.5) * 2;
    
    return totalScore + randomFactor;
  }

  /**
   * 获取棋子价值
   */
  getPieceValue(piece) {
    const values = {
      '帥': 10000, '帅': 10000, '將': 10000, '将': 10000,
      '車': 1000, '车': 1000,
      '馬': 500, '马': 500,
      '砲': 500, '炮': 500,
      '相': 250, '象': 250,
      '士': 250, '仕': 250,
      '兵': 100, '卒': 100
    };
    return values[piece.name] || 0;
  }

  /**
   * 高级位置价值评估
   */
  getAdvancedPositionValue(piece, row, col) {
    if (!this.positionTables[piece.name]) {
      return this.getPositionValue(piece, row, col);
    }
    
    const table = this.positionTables[piece.name];
    const adjustedRow = piece.color === COLORS.RED ? row : (9 - row);
    
    return table[adjustedRow] ? table[adjustedRow][col] || 0 : 0;
  }

  /**
   * 简化位置价值
   */
  getPositionValue(piece, row, col) {
    const centerBonus = Math.abs(4 - col) <= 1 ? 10 : 0;
    const advanceBonus = piece.color === COLORS.RED ? (9 - row) * 3 : row * 3;
    return centerBonus + advanceBonus;
  }

  // ========== 性能优化的快速方法 ==========

  /**
   * 快速紧急移动检查
   */
  findUrgentMoveFast(board, color) {
    // 1. 检查是否被将军 (简化版)
    if (this.isInCheck(board, color)) {
      const escapeMoves = getAllValidMoves(board, color);
      for (const move of escapeMoves) {
        // 🚫 即使被将军也不要做愚蠢的撤回
        if (this.isStupidUndo(move)) continue;
        
        const newBoard = cloneBoard(board);
        if (makeMove(newBoard, move.from, move.to).success) {
          if (!this.isInCheck(newBoard, color)) {
            return move; // 返回第一个能逃脱的移动
          }
        }
      }
    }
    
    // 2. 检查立即获胜 (简化版)
    const moves = getAllValidMoves(board, color);
    const opponentColor = color === COLORS.RED ? COLORS.BLACK : COLORS.RED;
    
    for (const move of moves.slice(0, 10)) { // 只检查前10个移动
      const target = board[move.to.row][move.to.col];
      if (target && (target.name === '帥' || target.name === '帅' || target.name === '將' || target.name === '将')) {
        return move; // 直接吃王
      }
    }
    
    // 3. 免费吃子 (简化版 - 只检查高价值目标)
    for (const move of moves.slice(0, 15)) {
      // 🚫 不要为了吃子而做愚蠢的撤回
      if (this.isStupidUndo(move)) continue;
      
      const target = board[move.to.row][move.to.col];
      if (target && target.color !== color) {
        const targetValue = this.getPieceValue(target);
        if (targetValue >= 400) { // 只考虑车、马、炮级别的
          return move;
        }
      }
    }
    
    return null;
  }
  
  /**
   * 检查是否为愚蠢的撤回移动
   */
  isStupidUndo(move) {
    if (!this.moveHistory || this.moveHistory.length === 0) return false;
    
    const lastMove = this.moveHistory[this.moveHistory.length - 1];
    if (!lastMove) return false;
    
    return move.from.row === lastMove.to.row && 
           move.from.col === lastMove.to.col &&
           move.to.row === lastMove.from.row && 
           move.to.col === lastMove.from.col;
  }

  /**
   * 快速移动排序
   */
  getOrderedMovesFast(board, color) {
    const moves = getAllValidMoves(board, color);
    
    // 简化排序：吃子移动 > 中心移动 > 其他
    return moves.sort((a, b) => {
      const scoreA = this.getMoveScoreFast(board, a);
      const scoreB = this.getMoveScoreFast(board, b);
      return scoreB - scoreA;
    });
  }

  /**
   * 快速移动评分
   */
  getMoveScoreFast(board, move) {
    let score = 0;
    
    // 🚫 严厉惩罚愚蠢的重复移动（快速版）
    if (this.moveHistory && this.moveHistory.length > 0) {
      const lastMove = this.moveHistory[this.moveHistory.length - 1];
      
      // 惩罚撤回移动
      if (lastMove && 
          move.from.row === lastMove.to.row && 
          move.from.col === lastMove.to.col &&
          move.to.row === lastMove.from.row && 
          move.to.col === lastMove.from.col) {
        score -= 50000;
      }
    }
    
    const target = board[move.to.row][move.to.col];
    if (target) {
      score += this.getPieceValue(target); // 吃子奖励
    }
    
    // 中心位置奖励
    if (this.isCenterSquare(move.to.row, move.to.col)) {
      score += 20;
    }
    
    return score;
  }

  /**
   * 快速棋盘评估
   */
  evaluateBoardFast(board, color) {
    let material = 0;
    let position = 0;
    let invasionPenalty = 0;
    
    const opponentColor = color === COLORS.RED ? COLORS.BLACK : COLORS.RED;
    
    for (let row = 0; row < 10; row++) {
      for (let col = 0; col < 9; col++) {
        const piece = board[row][col];
        if (piece) {
          const pieceValue = this.getPieceValue(piece);
          const posValue = this.getPositionValue(piece, row, col);
          
          if (piece.color === color) {
            material += pieceValue;
            position += posValue;
            
            // 进攻奖励
            const myInvasion = this.evaluateInvasionDepth({ row, col }, color);
            if (myInvasion > 0) {
              position += myInvasion * pieceValue * 0.5;
            }
          } else {
            material -= pieceValue;
            position -= posValue;
            
            // 防守惩罚
            const opponentInvasion = this.evaluateInvasionDepth({ row, col }, opponentColor);
            if (opponentInvasion > 0) {
              invasionPenalty += opponentInvasion * pieceValue * 2;
            }
          }
        }
      }
    }
    
    return material + position - invasionPenalty;
  }

  /**
   * 快速静止搜索
   */
  quiescenceSearchFast(board, alpha, beta, color, depth) {
    const standPat = this.evaluateBoardFast(board, color);
    
    if (depth <= 0 || standPat >= beta) {
      return standPat;
    }
    
    alpha = Math.max(alpha, standPat);
    
    // 只考虑高价值吃子
    const captures = this.getCaptureMoves(board, color).filter(move => {
      const target = board[move.to.row][move.to.col];
      return target && this.getPieceValue(target) >= 400;
    });
    
    for (const move of captures.slice(0, 5)) { // 限制数量
      const newBoard = cloneBoard(board);
      if (makeMove(newBoard, move.from, move.to).success) {
        const value = -this.quiescenceSearchFast(newBoard, -beta, -alpha, 
                                                color === COLORS.RED ? COLORS.BLACK : COLORS.RED, 
                                                depth - 1);
        
        if (value >= beta) return beta;
        alpha = Math.max(alpha, value);
      }
    }
    
    return alpha;
  }

  /**
   * 快速棋盘哈希
   */
  getBoardHashFast(board) {
    let hash = '';
    // 只取关键位置的哈希，减少计算
    for (let row = 0; row < 10; row += 2) {
      for (let col = 0; col < 9; col += 2) {
        const piece = board[row][col];
        hash += piece ? piece.name[0] : '0';
      }
    }
    return hash;
  }

  // ========== 原版辅助方法 ==========

  /**
   * 寻找紧急移动
   */
  findUrgentMove(board, color) {
    // 1. 检查是否被将军，必须应将
    if (this.isInCheck(board, color)) {
      const escapeMoves = this.getEscapeFromCheckMoves(board, color);
      if (escapeMoves.length === 1) return escapeMoves[0];
      if (escapeMoves.length > 1) {
        // 选择最好的应将移动
        return this.selectBestEscapeMove(board, escapeMoves, color);
      }
    }
    
    // 2. 检查是否有立即获胜的移动
    const winningMove = this.findWinningMove(board, color);
    if (winningMove) return winningMove;
    
    // 3. 检查是否有免费吃子的机会
    const freeCaptureMove = this.findFreeCaptureMove(board, color);
    if (freeCaptureMove) return freeCaptureMove;
    
    return null;
  }

  /**
   * 检查是否被将军
   */
  isInCheck(board, color) {
    const kingPos = this.findKing(board, color);
    if (!kingPos) return false;
    
    const opponentColor = color === COLORS.RED ? COLORS.BLACK : COLORS.RED;
    const opponentMoves = getAllValidMoves(board, opponentColor);
    
    return opponentMoves.some(move => 
      move.to.row === kingPos.row && move.to.col === kingPos.col
    );
  }

  /**
   * 寻找王的位置
   */
  findKing(board, color) {
    const kingName = color === COLORS.RED ? '帥' : '將';
    for (let row = 0; row < 10; row++) {
      for (let col = 0; col < 9; col++) {
        const piece = board[row][col];
        if (piece && piece.name === kingName && piece.color === color) {
          return { row, col };
        }
      }
    }
    return null;
  }

  /**
   * 获取应将移动
   */
  getEscapeFromCheckMoves(board, color) {
    const allMoves = getAllValidMoves(board, color);
    const escapeMoves = [];
    
    for (const move of allMoves) {
      const newBoard = cloneBoard(board);
      if (makeMove(newBoard, move.from, move.to).success) {
        if (!this.isInCheck(newBoard, color)) {
          escapeMoves.push(move);
        }
      }
    }
    
    return escapeMoves;
  }

  /**
   * 寻找获胜移动
   */
  findWinningMove(board, color) {
    const moves = getAllValidMoves(board, color);
    const opponentColor = color === COLORS.RED ? COLORS.BLACK : COLORS.RED;
    
    for (const move of moves) {
      const newBoard = cloneBoard(board);
      if (makeMove(newBoard, move.from, move.to).success) {
        // 检查是否将死对手
        if (this.isInCheck(newBoard, opponentColor)) {
          const opponentEscapes = this.getEscapeFromCheckMoves(newBoard, opponentColor);
          if (opponentEscapes.length === 0) {
            return move; // 将死对手
          }
        }
      }
    }
    
    return null;
  }

  /**
   * 寻找免费吃子移动
   */
  findFreeCaptureMove(board, color) {
    const moves = getAllValidMoves(board, color);
    
    for (const move of moves) {
      const target = board[move.to.row][move.to.col];
      if (target && target.color !== color) {
        // 简单检查：如果目标位置没有被保护
        if (!this.isSquareDefended(board, move.to.row, move.to.col, target.color)) {
          return move;
        }
      }
    }
    
    return null;
  }

  /**
   * 检查位置是否被保护
   */
  isSquareDefended(board, row, col, defendingColor) {
    const defendingMoves = getAllValidMoves(board, defendingColor);
    return defendingMoves.some(move => 
      move.to.row === row && move.to.col === col
    );
  }

  /**
   * 评估王安全
   */
  evaluateKingSafety(board, color) {
    const kingPos = this.findKing(board, color);
    if (!kingPos) return -1000;
    
    let safety = 0;
    
    // 检查王周围的保护
    const protectors = this.countProtectors(board, kingPos, color);
    safety += protectors * 20;
    
    // 检查是否在安全位置（九宫格内）
    if (this.isInPalace(kingPos.row, kingPos.col, color)) {
      safety += 50;
    }
    
    // 检查逃跑路线
    const escapeRoutes = this.countEscapeRoutes(board, kingPos, color);
    safety += escapeRoutes * 10;
    
    return safety;
  }

  /**
   * 评估发展状况
   */
  evaluateDevelopment(board, color) {
    let development = 0;
    
    // 计算出动的子力
    const activePieces = this.countActivePieces(board, color);
    development += activePieces * 10;
    
    // 中心控制
    const centerControl = this.evaluateCenterControl(board, color);
    development += centerControl;
    
    return development;
  }

  /**
   * 评估特殊位置
   */
  evaluateSpecialPositions(board, color) {
    let bonus = 0;
    
    // 车占据开放文件
    bonus += this.evaluateRookOnOpenFile(board, color);
    
    // 马的位置
    bonus += this.evaluateKnightPositions(board, color);
    
    // 炮的位置
    bonus += this.evaluateCannonPositions(board, color);
    
    return bonus;
  }

  /**
   * 残局评估
   */
  evaluateEndgame(board, color) {
    let endgameScore = 0;
    
    // 王的活跃性在残局中更重要
    const kingPos = this.findKing(board, color);
    if (kingPos && this.isEndgame(board)) {
      const kingActivity = this.evaluateKingActivity(board, kingPos, color);
      endgameScore += kingActivity;
    }
    
    return endgameScore;
  }

  /**
   * 判断是否为残局
   */
  isEndgame(board) {
    let pieceCount = 0;
    for (let row = 0; row < 10; row++) {
      for (let col = 0; col < 9; col++) {
        if (board[row][col]) pieceCount++;
      }
    }
    return pieceCount <= 10; // 少于10个子认为是残局
  }

  // ========== 开局库 ==========

  /**
   * 初始化开局库
   */
  initializeOpeningBook() {
    this.openingBook = [
      // 红方开局
      { condition: 'start_red', moves: [
        { from: { row: 9, col: 1 }, to: { row: 7, col: 2 } }, // 马二进三
        { from: { row: 9, col: 7 }, to: { row: 7, col: 6 } }, // 马八进七
        { from: { row: 9, col: 1 }, to: { row: 7, col: 0 } }, // 马二进一
        { from: { row: 9, col: 7 }, to: { row: 7, col: 8 } }  // 马八进九
      ]},
      // 黑方开局
      { condition: 'start_black', moves: [
        { from: { row: 0, col: 1 }, to: { row: 2, col: 2 } }, // 马2进3
        { from: { row: 0, col: 7 }, to: { row: 2, col: 6 } }, // 马8进7
        { from: { row: 0, col: 1 }, to: { row: 2, col: 0 } }, // 马2进1
        { from: { row: 0, col: 7 }, to: { row: 2, col: 8 } }  // 马8进9
      ]}
    ];
  }

  /**
   * 获取开局移动
   */
  getOpeningMove(board, color) {
    // 简单的开局：优先出马
    const moves = getAllValidMoves(board, color);
    const horseMoves = moves.filter(move => {
      const piece = board[move.from.row][move.from.col];
      return piece && (piece.name === '马' || piece.name === '馬');
    });
    
    if (horseMoves.length > 0) {
      return horseMoves[Math.floor(Math.random() * horseMoves.length)];
    }
    
    return null;
  }

  // ========== 位置价值表 ==========

  /**
   * 初始化位置价值表
   */
  initializePositionTables() {
    this.positionTables = {
      '车': [
        [20, 20, 20, 20, 20, 20, 20, 20, 20],
        [30, 30, 30, 30, 30, 30, 30, 30, 30],
        [10, 10, 20, 30, 30, 30, 20, 10, 10],
        [10, 10, 20, 20, 20, 20, 20, 10, 10],
        [10, 10, 20, 20, 20, 20, 20, 10, 10],
        [10, 10, 20, 20, 20, 20, 20, 10, 10],
        [10, 10, 20, 20, 20, 20, 20, 10, 10],
        [10, 10, 20, 30, 30, 30, 20, 10, 10],
        [30, 30, 30, 30, 30, 30, 30, 30, 30],
        [20, 20, 20, 20, 20, 20, 20, 20, 20]
      ],
      '马': [
        [0,  0,  0,  0,  0,  0,  0,  0,  0],
        [0,  0,  0,  0,  0,  0,  0,  0,  0],
        [10, 30, 20, 20, 20, 20, 20, 30, 10],
        [10, 20, 30, 30, 30, 30, 30, 20, 10],
        [10, 20, 30, 40, 40, 40, 30, 20, 10],
        [10, 20, 30, 40, 40, 40, 30, 20, 10],
        [10, 20, 30, 30, 30, 30, 30, 20, 10],
        [10, 30, 20, 20, 20, 20, 20, 30, 10],
        [0,  0,  0,  0,  0,  0,  0,  0,  0],
        [0,  0,  0,  0,  0,  0,  0,  0,  0]
      ],
      '炮': [
        [20, 20, 20, 20, 20, 20, 20, 20, 20],
        [10, 10, 10, 10, 10, 10, 10, 10, 10],
        [10, 10, 20, 30, 30, 30, 20, 10, 10],
        [0,  0,  20, 20, 20, 20, 20, 0,  0],
        [0,  0,  20, 20, 20, 20, 20, 0,  0],
        [0,  0,  20, 20, 20, 20, 20, 0,  0],
        [0,  0,  20, 20, 20, 20, 20, 0,  0],
        [10, 10, 20, 30, 30, 30, 20, 10, 10],
        [10, 10, 10, 10, 10, 10, 10, 10, 10],
        [20, 20, 20, 20, 20, 20, 20, 20, 20]
      ]
    };
    
    // 复制相同价值表给对应的繁体字
    this.positionTables['車'] = this.positionTables['车'];
    this.positionTables['馬'] = this.positionTables['马'];
    this.positionTables['砲'] = this.positionTables['炮'];
  }

  // ========== 更多辅助方法 ==========

  /**
   * 获取吃子移动
   */
  getCaptureMoves(board, color) {
    const moves = getAllValidMoves(board, color);
    return moves.filter(move => {
      const target = board[move.to.row][move.to.col];
      return target && target.color !== color;
    });
  }

  /**
   * 获取棋盘哈希值
   */
  getBoardHash(board) {
    let hash = '';
    for (let row = 0; row < 10; row++) {
      for (let col = 0; col < 9; col++) {
        const piece = board[row][col];
        hash += piece ? `${piece.color[0]}${piece.name}` : '00';
      }
    }
    return hash;
  }

  /**
   * 更新杀手移动
   */
  updateKillerMove(move, depth) {
    if (!this.killerMoves[depth]) this.killerMoves[depth] = [];
    
    const moveKey = this.getMoveKey(move);
    if (!this.killerMoves[depth].includes(moveKey)) {
      this.killerMoves[depth].unshift(moveKey);
      if (this.killerMoves[depth].length > 2) {
        this.killerMoves[depth].pop();
      }
    }
  }

  /**
   * 检查是否为杀手移动
   */
  isKillerMove(move, depth) {
    if (!this.killerMoves[depth]) return false;
    const moveKey = this.getMoveKey(move);
    return this.killerMoves[depth].includes(moveKey);
  }

  /**
   * 更新历史启发
   */
  updateHistory(move, depth) {
    const moveKey = this.getMoveKey(move);
    this.historyTable[moveKey] = (this.historyTable[moveKey] || 0) + depth * depth;
  }

  /**
   * 获取移动键值
   */
  getMoveKey(move) {
    return `${move.from.row}${move.from.col}${move.to.row}${move.to.col}`;
  }

  /**
   * 比较两个移动是否相等
   */
  movesEqual(move1, move2) {
    return move1.from.row === move2.from.row && 
           move1.from.col === move2.from.col &&
           move1.to.row === move2.to.row && 
           move1.to.col === move2.to.col;
  }

  /**
   * 移动转字符串
   */
  moveToString(move) {
    if (!move) return 'null';
    return `(${move.from.row},${move.from.col})->(${move.to.row},${move.to.col})`;
  }

  /**
   * 检查是否为中心格子
   */
  isCenterSquare(row, col) {
    return row >= 3 && row <= 6 && col >= 3 && col <= 5;
  }

  /**
   * 检查是否为边缘格子
   */
  isEdgeSquare(row, col) {
    return row === 0 || row === 9 || col === 0 || col === 8;
  }

  /**
   * 检查是否在九宫格内
   */
  isInPalace(row, col, color) {
    if (color === COLORS.RED) {
      return row >= 7 && row <= 9 && col >= 3 && col <= 5;
    } else {
      return row >= 0 && row <= 2 && col >= 3 && col <= 5;
    }
  }

  // 简化实现的辅助方法
  selectBestEscapeMove(board, moves, color) { return moves[0]; }
  countProtectors(board, kingPos, color) { return 2; }
  countEscapeRoutes(board, kingPos, color) { return 3; }
  countActivePieces(board, color) { return 5; }
  evaluateCenterControl(board, color) { return 0; }
  evaluateRookOnOpenFile(board, color) { return 0; }
  evaluateKnightPositions(board, color) { return 0; }
  evaluateCannonPositions(board, color) { return 0; }
  evaluateKingActivity(board, kingPos, color) { return 0; }

  /**
   * 设置AI难度 (性能优化版)
   */
  setDifficulty(difficulty) {
    this.difficulty = difficulty;
    
    // 根据难度调整性能参数（允许更深搜索）
    this.maxDepth = Math.min(difficulty.depth, 6);
    this.maxNodes = this.calculateMaxNodes(difficulty);
    
    console.log(`🎚️ AI难度设置: ${difficulty.name}, 深度: ${this.maxDepth}, 节点限制: ${this.maxNodes}`);
  }

  /**
   * 获取当前难度
   */
  getDifficulty() {
    return this.difficulty;
  }
}

// 导出单例实例
export const chessAI = new ChessAI();
